import logging
from django.views.decorators.http import require_GET
from common.utils.decorator import response_wrapper, validate_form
from common.utils.api import token_required
from .form import (
    GameReportForm,
    GameAggregateAnalysisForm,
    BetAnalysisForm
)
from common.cp.maestro import product_event_handler
from common.permission.handler import process_resp_items, get_key_mapper
from common.utils.export import export_file
from common.mg_core import mg

_LOGGER = logging.getLogger(__name__)

GAME_PAGE_ID = {
    'bull': '2001',
    'lottery': '2002'
}


@require_GET
@response_wrapper
@token_required
@validate_form(GameReportForm)
def get_game_report(req, cleaned_data):
    merchant_name = req.merchant_name
    role_id = req.merchant_role['id']
    game_type = cleaned_data['game_type']
    game_id = cleaned_data['game_id']
    time_range = cleaned_data['time_range']
    sort_by = cleaned_data['sort_by'] or '-updated_at'
    to_export_file = cleaned_data['to_export_file']
    condition = dict(game_type=game_type, game_id=game_id, base_time={'$gte': time_range[0], '$lt': time_range[1]})
    disable_paginate = True if to_export_file else False
    game_reports, total_count = mg.get_report(merchant_name, 'term_report', condition, sort_key=sort_by,
                                              disable_paginate=disable_paginate)
    resp_items = [report for report in game_reports]
    key_mapper = get_key_mapper(merchant_name, GAME_PAGE_ID[game_id], role_id)
    resp_items = process_resp_items(resp_items, key_mapper)
    if to_export_file:
        return export_file(req, resp_items, key_mapper, file_name='_'.join([str(game_id), 'game_report']))
    return dict(list=resp_items, total_count=total_count, key_mapper=key_mapper)


@require_GET
@response_wrapper
@token_required
@validate_form(GameAggregateAnalysisForm)
def get_game_aggregate_analysis(req, cleaned_data):
    merchant_name = req.merchant_name
    role_id = req.merchant_role['id']
    game_type = cleaned_data['game_type'] or 'lottery'
    game_id_list = cleaned_data['game_id_list'] or ['all']
    user_type = cleaned_data['user_type']
    time_range = cleaned_data['time_range']
    sort_by = cleaned_data['sort_by'] or '-updated_at'
    size, page = cleaned_data['size'], cleaned_data['page']
    to_export_file = cleaned_data['to_export_file']
    condition = dict(game_id={'$in': game_id_list}, updated_at={'$gte': time_range[0], '$lt': time_range[1]})
    disable_paginate = True if to_export_file else False
    collection = 'game_dwc_aggregate_report' if game_type == 'dwc' else 'game_lottery_aggregate_report'
    game_reports, total_count = mg.get_report(merchant_name, collection, condition, sort_key=sort_by, page=page,
                                              size=size, disable_paginate=disable_paginate, user_type=user_type)
    key_mapper = get_key_mapper(merchant_name, '2004', role_id)
    resp_items = process_resp_items(game_reports, key_mapper)
    if to_export_file:
        return export_file(req, resp_items, key_mapper, file_name='game_aggregate_report')
    return dict(list=resp_items, total_count=total_count, key_mapper=key_mapper)


@require_GET
@response_wrapper
@token_required
@validate_form(BetAnalysisForm)
def get_bet_user_analysis(req, cleaned_data):
    merchant_name, role_id = req.merchant_name, req.merchant_role['id']
    index = req.es_index
    chn_filter_list = cleaned_data['channel']
    sort_by = cleaned_data['sort_by'] or '-updated_at'
    time_range = cleaned_data['time_range']
    registered_time_range = cleaned_data['registered_time_range']
    user_id = cleaned_data['user_id']
    game_id = cleaned_data['game_type'] or 'lottery'
    game_id_list = cleaned_data['game_id_list'] or ['all']
    size, page = cleaned_data['size'], cleaned_data['page']
    amount_max = cleaned_data['amount_max']
    amount_min = cleaned_data['amount_min']
    to_export_file = cleaned_data['to_export_file']
    disable_paginate = True if to_export_file else False
    analysis_result, total_count = product_event_handler.get_user_analysis_report(
        index, amount_max=amount_max, amount_min=amount_min, user_id=user_id, chn_filter_list=chn_filter_list,
        time_range=time_range, registered_time_range=registered_time_range, game_id=game_id, game_id_list=game_id_list,
        disable_paginate=disable_paginate, sort_by=sort_by, page=page, size=size
    )
    key_mapper = get_key_mapper(merchant_name, '2005', role_id, game_id=game_id)
    resp_items = process_resp_items(analysis_result, key_mapper)
    if to_export_file:
        file_name = 'dwc_bet_user_analysis' if game_id == "dwc" else 'lottery_bet_user_analysis'
        return export_file(req, resp_items, key_mapper, file_name=file_name, maximum_row=200000)
    return dict(list=resp_items, total_count=total_count, key_mapper=key_mapper)


@require_GET
@response_wrapper
def get_game_aggregate_analysis_preset(req):
    return dict(preset=product_event_handler.get_game_aggregate_analysis_preset())
